package v1

import (
	"strings"
	"yuanxin-admin/internal/common/auth"
	"yuanxin-admin/internal/common/ioc"
	"yuanxin-admin/internal/dto"
	"yuanxin-admin/internal/service"
	"yuanxin-admin/internal/vo"

	"gitee.com/botaoshow/yuanxin/web/common/database"
	"gitee.com/botaoshow/yuanxin/web/response"
	"github.com/gin-gonic/gin"
)

type SysRoleController struct {
	sysRoleService service.ISysRoleService
}

func NewSysRoleController() *SysRoleController {
	return &SysRoleController{
		sysRoleService: ioc.Inject[service.ISysRoleService]((service.ISysRoleService)(nil)),
	}
}

func (s *SysRoleController) Query(c *gin.Context) {
	sql := `
SELECT id,
               role_name                                              as label,
               role_code                                              as [value],
               (select count(*) from sys_role_url where sys_role_url.role_id = sys_role.id) as perm_count
        FROM sys_role
        order by id
        `
	sql = strings.ReplaceAll(sql, "[", "`")
	sql = strings.ReplaceAll(sql, "]", "`")
	var list []*vo.RoleVO
	database.Db.Raw(sql).Scan(&list)
	response.Success(c, list)
}

func (s *SysRoleController) AddUrl(c *gin.Context) {
	var d dto.RoleUrlDTO
	if err := c.ShouldBindJSON(&d); err != nil {
		response.Fail(c, err.Error())
		return
	}
	roleIds := d.RoleIds
	urlIds := d.UrlIds
	_, err := s.sysRoleService.AddUrl(c, roleIds, urlIds)
	if err != nil {
		response.Fail(c, err.Error())
		return
	}
	auth.FlushUrlRolesCache(c)
	response.SuccessDefault(c)

}

func (s *SysRoleController) RemoveUrl(c *gin.Context) {
	var d dto.RoleUrlDTO
	if err := c.ShouldBindJSON(&d); err != nil {
		response.Fail(c, err.Error())
		return
	}
	roleIds := d.RoleIds
	urlIds := d.UrlIds
	_, err := s.sysRoleService.RemoveUrl(c, roleIds, urlIds)
	if err != nil {
		response.Fail(c, err.Error())
		return
	}
	auth.FlushUrlRolesCache(c)
	response.SuccessDefault(c)

}
